<template>
  <div id="LabInstrSetup">
    <div class="bodyContent">
      <el-tabs type="border-card">
        <el-tab-pane label="抗生素">
          <Splitpanes class="area">
            <Pane size="55">
              <vxe-toolbar perfect>
                <template #buttons>
                  <span class="smallToolTitle">名称模糊查找:</span>
                  <vxe-input v-model="form.antName" placeholder="名称" class="vxeInputSearch" type="text" clearable @clear="findAntibioticsDictPageList"></vxe-input>

                  <vxe-button type="text" icon="vxe-icon-search" class="button-blue SearchBtn" content="查询" :loading="loading" @click="findAntibioticsDictPageList"></vxe-button>

                  <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="handleDelete"></vxe-button>
                </template>
              </vxe-toolbar>

              <div class="tableBox">
                <vxe-table ref="antibioticsDictTable" border align="left" class="mytable-scrollbar" height="auto" :data="antibioticsDictList" :expand-config="{ expandAll: true, reserve: true }" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
                    isArrow: true,
                    isTab: true,
                    isEdit: true
                  }" :edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true }" resizable show-overflow keep-source @current-change="roleRowClick">
                  <vxe-column type="checkbox" width="30px"></vxe-column>
                  <vxe-column field="antName" title="名称" width="100"> </vxe-column>
                  <vxe-column field="antCode" title="编码" width="60"> </vxe-column>
                  <vxe-column field="verificationPrice" title="效价" width="100"> </vxe-column>
                  <vxe-column field="englishName" title="英文名称" width="100"> </vxe-column>
                  <vxe-column field="inputCode" title="助记符" width="100"> </vxe-column>
                  <vxe-column field="humanUse" title="是否人用" width="100" align="center">
                    <template #default="{ row }">
                      <el-tag type='danger' v-if="row.humanUse === '0'">否</el-tag>
                      <el-tag type='success' v-else-if="row.humanUse === '1'">是</el-tag>
                      <span v-else>——</span>
                    </template>
                  </vxe-column>
                  <vxe-column field="beastUse" title="是否兽用" width="100" align="center">
                    <template #default="{ row }">
                      <el-tag type='danger' v-if="row.beastUse === '0'">否</el-tag>
                      <el-tag type='success' v-else-if="row.beastUse === '1'">是</el-tag>
                      <span v-else>—</span>
                    </template>
                  </vxe-column>
                  <vxe-column field="clsiOrder" title="Clsi顺序" width="100"> </vxe-column>
                  <vxe-column field="whonetAbxCode" title="WhonetAbxCode" width="100"> </vxe-column>
                  <vxe-column field="abxNumber" title="AbxNumber" width="100"> </vxe-column>
                  <vxe-column field="antType" title="抗生素分类" width="100"> </vxe-column>
                  <vxe-column field="studyType" title="研究分类" width="100"> </vxe-column>
                  <vxe-column field="whoCode" title="whoCode" width="100"> </vxe-column>
                </vxe-table>

                <el-pagination :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="page.totalResult" @size-change="handleSizeChange" @current-change="handleCurrentChange" />

              </div>
            </Pane>
            <Pane size="45">
              <!-- 检验仪器基本信息表单-->
              <BacAntibioticsDictForm ref="refFormData" @getTableData="findAntibioticsDictPageList" />
            </Pane>
          </Splitpanes>
        </el-tab-pane>
        <el-tab-pane label="操作日志">
          <LogInfo requestUrl="/lis/bacAntibioticsDict"></LogInfo>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import Breadcrumb from '@/components/Breadcrumb.vue';
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { pageSizes, formatDateTime } from '../../utils/common';
import { Splitpanes, Pane } from 'splitpanes';
import { AppStore } from '../../stores/store';
import XEUtils from 'xe-utils';
import { VXETable } from 'vxe-table';
import { VxeNotifyType, VxeMessage } from '../../utils/CommonMessage';
import BacAntibioticsDictForm from './StaBacAntibioticsDictForm.vue'; //检验仪器基本信息表单
import LogInfo from '@/components/LogInfo.vue'; //日志

defineExpose({ initPage });

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let store = AppStore();
let form = reactive({
  antName: '' //名称
});

let antibioticsDictList: any = reactive([]); //抗生素列表

// 条数/页
// 分页
let page = reactive({
  currentPage: 1,
  pageSize: 10,
  totalResult: 0
});

let loading = ref(false); //查询按钮加载

let saveLoading = ref(false);

let refFormData: any = ref(null); //信息表单ref

// 方法定义区 =============

let addSeq = 0;
// 获取检验仪器表格数据
function findAntibioticsDictPageList() {
  loading.value = true;
  antibioticsDictList.length = 0;
  const url = '/lis/staAntibioticsDict/findAntibioticsDictPageList';
  proxy.$http
    .get(url, {
      params: {
        pageIndex: page.currentPage,
        pageSize: page.pageSize,
        antName: form.antName
      }
    })
    .then((res: any) => {
      antibioticsDictList.push(...res.data.records);
      page.totalResult = res.data.total;
      addSeq = res.data.total + 1;
      refFormData.value.initAddPage(addSeq); //传递给右侧基本信息表单
      roleRowClick({
        row: antibioticsDictList[0],
        rowIndex: 0
      });
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('搜索抗生素列表异常', VxeNotifyType.error);
    });
}

//删除按钮
function handleDelete() {
  const selectRows = (proxy.$refs.antibioticsDictTable as any).getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请勾选需要删除的仪器', VxeNotifyType.warning);
    return;
  } else {
    proxy
      .$confirm('您确定要删除当前选中的这条数据吗?', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const commaSeparatedIds = selectRows.map((row) => row.id);
        const commaSeparatedNames = selectRows.map((row) => row.instrName);
        const ids = commaSeparatedIds.join(',');
        const names = commaSeparatedNames.join(',');
        const data = { ids: ids, names: names };
        const url = '/lis/staAntibioticsDict/deleteAntibioticsDict';
        proxy.$http
          .post(url, data)
          .then((res: any) => {
            findAntibioticsDictPageList();
            refFormData.value.clearFormData(); //调用子组件的清空表单方法
            VxeMessage(res.status.msg, VxeNotifyType.success);
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      });
  }
}

// 点击表格当前行
function roleRowClick({ row, rowIndex }: any) {
  // obj:any
  // console.log('------------------row', obj.row);
  // refFormData.value.initPage(obj.row); //传递给右侧基本信息表单
  refFormData.value.initPage(row); //传递给右侧基本信息表单
  (proxy.$refs.antibioticsDictTable as any).setCurrentRow(row);
}

//下拉选择之后触发保存当前
function selectchange(e: any) {
  e.aimKeys.forEach((item: any) => {
    if (e.isChild) {
      instrSetupList[e.childIndex][item.targetField] = e.row[item.sourceField];
      if (item.targetField === 'reportUnitEntity') {
        instrSetupList[e.childIndex].groupNo = e.row[item.sourceField].id;
      }
    } else {
      //表单用
    }
  });
}

// 点击修改新增保存
async function saveList() {
  saveLoading.value = true;
  // 获取表格实例
  const $Xtable = antibioticsDictTable.value;
  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords();

    // 拿到列表中id为空的为新增
    const InsertRecords = await $Xtable.getInsertRecords().filter((m: any) => {
      return m.id === '';
    });

    // 遍历发起请求  将筛选出有id的每一个对象（修改过的） 作为参数传递给后端
    updateRecords.forEach((e: any) => {
      let data = e;

      proxy.$http
        .post('/lis/instrSetup/edit', data)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('修改成功', VxeNotifyType.success);
          } else {
            return;
          }
        })
        .catch((err: any) => {
          VxeMessage('修改异常', VxeNotifyType.error);
        });
    });

    //新增
    InsertRecords.forEach((e: any) => {
      proxy.$http
        .post('/lis/instrSetup/addInstrSetup', e)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('创建成功', VxeNotifyType.success);
          } else {
            return;
          }
        })
        .catch((err: any) => {
          VxeMessage('创建异常', VxeNotifyType.error);
        });
    });
    setTimeout(() => {
      findAntibioticsDictPageList();
      saveLoading.value = false;
    }, 500);
  } else {
    return;
  }
}

//这个月第一天日期
function getThisMonthFirstDay() {
  let today = new Date();
  today.setDate(1);
  today.setHours(0, 0, 0, 0);
  return today;
}
//当前日期
function getThisMonthNewDay() {
  let today = new Date();
  return today;
}

function formatOperateTime({ cellValue, row, column }) {
  // 假设cellValue是一个时间戳，你可以使用Date对象将其格式化为包含毫秒的形式
  const date = new Date(cellValue);
  return formatDateTime(date, 'yyyy-MM-dd hh:mm:ss.SSS'); // 这会返回包含毫秒的 ISO 8601 格式的时间字符串
}
//更换一页显示数量
function handleSizeChange(val) {
  page.pageSize = val;
  findAntibioticsDictPageList();
}

// 点击下一页
function handleCurrentChange(val) {
  page.currentPage = val;
  findAntibioticsDictPageList();
}

function initPage() {
  findAntibioticsDictPageList();
}
</script>

<style lang="scss" scoped>
#LabInstrSetup {
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    .el-tabs {
      height: 100%;

      :deep(.el-tabs__content) {
        height: calc(100% - 39px);
        padding: 0px;

        #pane-0,
        #pane-1 {
          height: 100%;
        }
      }
    }

    .area {
      background-color: $base-white;
    }

    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }

    // 查询按钮
    .SearchBtn {
      margin-right: 5px;
    }

    .tableBox {
      height: calc(100% - 40px);

      .vxe-table {
        height: calc(100% - 32px);

        :deep(.vxe-table--render-wrapper) {
          height: 100%;

          .vxe-table--main-wrapper {
            height: 100%;

            .vxe-table--body-wrapper {
              height: calc(100% - 26px) !important;
            }
          }
        }
      }
    }
  }
}
</style>
